﻿using M.Warehouse.API.Application.Command.ReservoirsCommand;
using M.Warehouse.Domain;
using M.Warehouse.Domain.DTO;
using M.Warehouse.Repository.WarehouseInterface;
using MediatR;

namespace M.Warehouse.API.Application.CommandHandlers.ReservoirsHandlers
{
    public class ReservoirsShowCommandHandlers : IRequestHandler<ReservoirsShowCommand, PageDTO<ReservoirsShowDTO>>
    {
        private readonly IWarehouseWRepository _warehouseWRepository;
        private readonly IReservoirsWRepository _repository;
        public ReservoirsShowCommandHandlers(IReservoirsWRepository repository, IWarehouseWRepository warehouseWRepository)
        {
            _repository = repository;
            _warehouseWRepository = warehouseWRepository;
        }

        public async Task<PageDTO<ReservoirsShowDTO>> Handle(ReservoirsShowCommand request, CancellationToken cancellationToken)
        {
            var reservoirs = (await _repository.GetAllAsync()).Where(x => !x.IsDeleted);
            var warehouse = await _warehouseWRepository.GetAllAsync();
            var list = (from a in reservoirs
                        join b in warehouse on a.WarehouseId equals b.WarehouseId
                        where !a.IsDeleted
                        select new ReservoirsShowDTO
                        {
                            ReservoirId=a.ReservoirId,
                            WarehouseId=b.WarehouseId,
                            ReservoirName=a.ReservoirName,
                            WarehouseName =b.WarehouseName,
                            ReservoirNo=a.ReservoirNo,
                            ReservoirArea=a.ReservoirArea,
                            BinLocationNum=a.BinLocationNum,
                            ReservoirRemark=a.ReservoirRemark,
                            CreatedBy=a.CreatedBy,
                            CreatedDate=a.CreatedDate,
                        }).ToList();
            if (!string.IsNullOrEmpty(request.ReservoirName))
            {
                list = list.Where(x => x.ReservoirName.Contains(request.ReservoirName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ReservoirNo))
            {
                list = list.Where(x => x.ReservoirNo.Contains(request.ReservoirNo)).ToList();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = list.Count();
            }
            PageDTO<ReservoirsShowDTO> page = new PageDTO<ReservoirsShowDTO>();
            page.TotalCount = list.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list = list.OrderByDescending(x => x.CreatedDate).Skip((int)(request.PageIndex - 1) * (int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
